# encoding:utf8


import os
import sys
import shutil
import json
from ccpm.pmbase import PluginBase, PmUtil
from argparse import ArgumentParser
from mgamedev.py_lib.decorator import singleton
from ccpm.conffac import PackConf, PluginConf
from ccpm.glan import Lan
from mgamedev.py_lib.luabase import LuabaseTool
from ccpm.net import NetUtil
import copy
from ccpm.constants import Constant
import uuid
import zipfile
import operator
import hashlib
from ccpm.model.modelusr import ModelUsr
from ccpm.auth.gitee_auth import GiteeLogin
from ccpm.constants import Constant


'''
packcfg.json 
{
    "same with publish"
}
'''


@singleton
class UploadtoolPlugin(PluginBase):

    PLUGIN_INFO = dict(
        name="uploadtool",
        help="upload tool "
    )

    IS_CHKLOCAL_USR = True

    def __init__(self):
        super().__init__(self.PLUGIN_INFO)
        self._packconf = None

    def __chk_format():
        # todo: Chk the conf fmt forbiden upload wrong global-config
        return True

    def parser_config(self, argparser):
        super().parser_config(argparser)
        argparser.add_argument("-f", dest="tfile",
                               help=Lan.p(self.name, "DESC_UPLOAD_TARFILE"))
        argparser.add_argument("-n", dest="tname",
                               help=Lan.p(self.name, "DESC_UPLOAD_TARNAME"))
        argparser.add_argument("-s", dest="tver",
                               help=Lan.p(self.name, "DESC_UPLOAD_TARVER"))
        argparser.add_argument("-d", dest="tdesc",
                               help=Lan.p(self.name, "DESC_UPLOAD_TARDESC"))

    def __chk_publish_enable(self):
        self.__chk_tools_exist()
        self.__chk_same_giteeusr()

    def __chk_same_giteeusr(self):
        # todo
        return True

    def __chk_tools_exist(self):
        name = self._packconf["name"]
        pinfo_list = NetUtil.tools_exist_chk(name)
        if isinstance(pinfo_list, list):
            for pinfo in pinfo_list:
                if pinfo["ver"] == self._packconf["ver"]:
                    self.err_break(
                        Lan.p(self.name, "ERR_REMOTE_PLUGINEXIST", name,
                              str(pinfo["ver"])))

    def __chk_usr(self):
        if not self.IS_CHKLOCAL_USR:
            return True
        if not PmUtil.chk_usr_enable():
            self.err_break(Lan.p(self.name, "ERR_GET_GITEEUSR_FAILED"))

    def run(self, argpars):
        super().run(argpars)
        tfile = argpars.tfile
        tname = argpars.tname
        tver = argpars.tver
        tdesc = argpars.tdesc
        if not (tfile and tname and tver and tdesc):
            self.err_break(Lan.p(self.name, "ERR_NOT_MUSTPARAMS"))

        self._packconf = dict(
            name=tname,
            ver=tver,
            desc=tdesc,
            license="MIT",
        )
        # chk local-user
        self.__chk_usr()
        # chk entry and plugin-info
        self.__chk_publish_enable()
        self.logger.info(Lan.p(self.name, "DESC_UPLOADING_FILE"))
        # start pack
        fzip = tfile
        fzip_size = round((os.path.getsize(fzip) / float(1024)), 2)
        fzip_md5 = PmUtil.get_file_md5(fzip)
        # uploading
        pwd = PluginConf().get("_sftp").pwd
        remote_path = PluginConf().get("_sftp").remote_path
        ret = NetUtil.sftp_upload(pwd, os.path.abspath(
            fzip), remote_path)
        if ret:
            dbinfo = copy
            self._packconf["contsize"] = fzip_size
            self._packconf["md5"] = fzip_md5
            self._packconf["gitee_usr"] = ModelUsr().get_name()
            self._packconf["filename"] = tfile.split(os.sep)[-1]
            self.logger.info("upload info:%s", str(self._packconf))
            ret = NetUtil.add_tool_db(self._packconf)
            if (not ret):
                self.err_break(Lan.p(self.name, "ERR_INSERT_DB_FAILED"))
        os.remove(os.path.abspath(fzip))


__all__ = [
    "UploadtoolPlugin"
]
